# coding=utf-8
"""
Copyright (c) Huawei Technologies Co., Ltd. 2020-2028. All rights reserved.
Description:
FileName：start.py
Author: h00568282/huangbin 
Create Date: 2025/9/18 16:52
Notes:

"""

import os
import sys
import time
import subprocess
from typing import List

from sys_intd.constant import PROJECT_MCP_CENTER_PATH as MCP_CENTER_PATH
from sys_intd.exceptions import MCPServerStartError
from sys_intd.manager import McpServerManager
from sys_intd.schema import MCPCenterServerConfig, ServerConfig, STDIOServerConfig

def start(server_name: str = "cache-miss-audit", http: bool = False, sse: bool = False, port: str = "0.0.0.0",
          host: int = 5500) -> List[str]:
    output_lines = []
    mcp_server_manager = McpServerManager()

    if not os.path.exists(MCP_CENTER_PATH):
        raise MCPServerStartError(
            f"Install mcp center before, project https://gitee.com/zxstty/mcp_center into {MCP_CENTER_PATH}")

    os.environ["PYTHONPATH"] = MCP_CENTER_PATH
    output_lines.append(f"\n[bold cyan]Prepare start server '{server_name}'")
    output_lines.append(f"\n[bold]PYTHONPATH: {MCP_CENTER_PATH}")

    if mcp_server_manager.server_exists(server_name):
        output_lines.append(f'''[bold]'{server_name}' has installed.''')

        server_config = mcp_server_manager.get_server(server_name)
        if isinstance(server_config, MCPCenterServerConfig):
            python_cmd = [server_config.command, *server_config.args]
            output_lines.append(f"[bold]Start command: {python_cmd}")
            process = subprocess.Popen(python_cmd, cwd=MCP_CENTER_PATH)
            time.sleep(2)
            if process.poll() is None:
                output_lines.append(f"[bold cyan]Uvicorn running on {server_config.url}.")
                output_lines.append(f'''\n[bold]'{server_name}' start up ok, process id: {process.pid}.\n''')
            else:
                exit_code = process.poll()
                raise MCPServerStartError(
                    f'''\n[bold cyan]'{server_name}' start fail, process id: {process.pid}, exit_code: {exit_code}.\n''')
        elif isinstance(server_config, STDIOServerConfig):
            # todo for other mcp type
            output_lines.append(
                f'''\n[bold cyan]'{server_name}' start fail, other type mcp would match later.\n''')
            pass

    return output_lines


def main():
    start()


if __name__ == "__main__":
    main()
